package com.framework.boc.socket.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;

public class TimeServer {

    public static void main(String[] args) {
        ServerSocket server = null;
        try {
            server = new ServerSocket(8090);
            System.out.println("Time server started on 8090...");
            while (true) {
                Socket clientProxy = server.accept();
                new Thread(new TimeServerHandler(clientProxy)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


class TimeServerHandler implements Runnable {

    private Socket clientProxy;

    public TimeServerHandler(Socket clientProxy) {
        this.clientProxy = clientProxy;
    }

    @Override
    public void run() {
        BufferedReader reader = null;
        PrintWriter writer = null;

        try {
            reader = new BufferedReader(new InputStreamReader(clientProxy.getInputStream()));
            writer = new PrintWriter(clientProxy.getOutputStream());
            while (true) {
                String req = reader.readLine();
                if (req.equals("GET CURRENT TIME")) {
                    writer.println(Calendar.getInstance().getTime().toString());
                } else {
                    writer.println("BAD REQUEST");
                }
                writer.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
                writer.close();
                clientProxy.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
